# coding=utf-8
from datetime import timedelta
from flask import Flask, render_template, request, make_response, jsonify
from flask_sqlalchemy import SQLAlchemy
import config
import os
from flask_cors import *

basedir = os.path.abspath(os.path.dirname(__file__))


def create_app():
    # flask
    app = Flask(__name__, template_folder='./templates', static_folder="./templates", static_url_path="")

    # 解决跨域问题
    CORS(app, supports_credentials=True)

    # 配置数据库
    app.config.from_object(config)
    app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
    # gunicorn多进程禁用
    # app.config['SECRET_KEY'] = os.urandom(24)  # 设置为24位的字符,每次运行服务器都是不同的，所以服务器启动一次上次的session就清除。
    app.config['SECRET_KEY'] = 'yuepai'
    app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(days=7)  # 设置session的保存时间。

    # register blueprint
    from .apis import api_blueprint
    # from .apis.chat import chat_blueprint
    app.register_blueprint(api_blueprint)
    # app.register_blueprint(chat_blueprint)
    return app


def register_api():
    from .apis import api
    from .apis.user import ns as user_api
    from .apis.equipment import ns as equipment_api
    from .apis.lab import ns as lab_api

    api.add_namespace(user_api)
    api.add_namespace(equipment_api)
    api.add_namespace(lab_api)


app = create_app()
db = SQLAlchemy(app)

# register api namespace
register_api()


@app.route('/')
def cms():
    return render_template('index.html')
